import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import { IsLogin } from '../request/api'
const Index = () => import('../views/Index');
const Login = () => import('../views/Login');
const Home = () => import('../views/Home');
const Goods = () => import('../views/Goods');
const Thanks = () => import('../views/Thanks');
const GoodsDetail = () => import('../views/GoodsDetail');
const User = () => import('../views/User');
const Pay = () => import('../views/Pay');
const Cart = () => import('../views/Cart');

Vue.use(VueRouter)


// 下列三行代码是方式路由跳转时点击多次报出错误，进行错误抛出
//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


const routes = [
  // 注意这种路由的写法
  {
    path: '/',
    redirect: '/home',
    component: Index,
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'goods',
        component: Goods
      },
      {
        path: 'thanks',
        component: Thanks
      },
      {
        path: 'goodsdetail',
        name: 'goodsdetail',
        component: GoodsDetail
      },
      {
        path: 'pay',
        component: Pay
      },
      {
        path: 'cart',
        component: Cart,
        meta: {
          // 需要守卫
          auth: true
        }
      }
    ]
  },
  // {
  //   path: '/home',
  //   name: 'home',
  //   component: Index,
  //   children: [
  //     {
  //       path: '/',
  //       redirect: '/home/homes',
  //     },
  //     {
  //       path: 'homes',
  //       component: Home
  //     }
  //   ]
  // },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/user',
    name: 'user',
    component: User,
    meta: {
      // 需要守卫
      auth: true
    }
  }
]




const router = new VueRouter({
  routes,
  // 跳转路由的时候，页面不从最顶部开始显示的解决代码
  scrollBehavior() {
    return {x: 0, y: 0};
  }
})



// 路由守卫
router.beforeEach((to, from, next) => {
  IsLogin({}).then(res => {
    let data = res.data;
    if (data.state !== 1) {
      // 用户要登录
      if (to.meta.auth) {
        next('/login')
      } else {
        next()
      }
      // 注意这种写法
      // if (to.matched.some(record => record.meta.auth)) {
      //   // 用户未登录 需要跳转登录页面
      //   next('/login')
      // } else {
      //   next();
      // }
    } else {
      // 保存用户的信息
      store.commit('ISLOGIN', data);
      next();
    }
  })
})


export default router